<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>事件冒泡处理</title>
  <style>
    #div_green #div_blue #div_red {cursor: pointer;}
    #div_green {
      width: 150px;height: 150px;
      background-color: green;
      position: relative;
      text-align: center;
    }
    #div_blue {
      width: 100px;height: 100px;
      background-color: blue;
      position: absolute;top: 25px;left: 25px;
    }
    #div_red {
      width: 50px;height: 50px;
      background-color: red;
      position: absolute;top: 25px;left: 25px;
    }
    #div_red {left: 200px;}
  </style>
</head>

<body>
  <div id="div_green">
    <div id="div_blue">
      <div id="div_red"></div>
    </div>
  </div>

  <script>
    var div_green = document.getElementById("div_green");
    var div_blue = document.getElementById("div_blue");
    var div_red = document.getElementById("div_red");
    //捕获阶段
    div_green.addEventListener("click",
      function () {
        alert("click 捕获阶段 div_green");
      },
      true //是否在捕获阶段就提前触发,默认false
    );
    div_blue.addEventListener("click",
      function () {
        alert("click 捕获阶段 div_blue");
      },
      true
    );
    div_red.addEventListener("click",
      function () {
        alert("click 捕获阶段 div_red");
      },
      true
    );


    //冒泡阶段
    div_green.onclick = function (e) {
      alert("click 冒泡阶段 div_green");
    }
    div_blue.onclick = function (e) {
      alert("click 冒泡阶段 div_blue");
    }
    div_red.onclick = function (e) {
      alert("click 冒泡阶段 div_red");
      e = e || window.event;
      //阻止冒泡时的事件,但是不能阻止捕获时的事件
      //兼容
      if (typeof e.stopPropagation === "function") {
        // e.stopPropagation();
      } else {
        // e.cancelBubble = true;
      }

    }
  </script>
</body>

</html>